package ntd.util.frame.server.factory;

import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.ReflectUtil;
import ntd.block.server.ComServer;
import ntd.block.server.bo.ComServerInBo;
import ntd.block.server.impl.ComServerHttp;
import ntd.block.server.impl.ComServerTcp;
import ntd.util.config.common.exception.ComException;
import ntd.util.frame.server.context.ContextServer;
import ntd.util.config.common.enums.app.EnumServerAppType;

import java.util.HashMap;
import java.util.Map;

public class FactoryComServer {

    private static Map<EnumServerAppType, Class<? extends ComServer>> appTypeServerMap = new HashMap<>();

    static {
        appTypeServerMap.put(EnumServerAppType.SERVER_HTTP, ComServerHttp.class);
        appTypeServerMap.put(EnumServerAppType.SERVER_TCP, ComServerTcp.class);
    }

    /**
     * 根据上下文获取服务 - 通过type类型
     *
     * @param contextServer
     * @return
     */
    public static ContextServer initServer(ContextServer contextServer) {
        EnumServerAppType enumServerAppType = Opt.ofNullable(contextServer)
                .orElseThrow(() -> new ComException("contextServer 参数为空！")).getEnumServerAppType();
        Class<? extends ComServer> aClass = Opt.ofNullable(appTypeServerMap.get(enumServerAppType))
                .orElseThrow(() -> new ComException("找不到该类型的处理方式"));

        ComServerInBo comServerInBo = new ComServerInBo();
        comServerInBo.setPort(contextServer.getPort());
        comServerInBo.setHost(contextServer.getHost());

        ComServer comServer = ReflectUtil.newInstance(aClass);
        comServer.init(comServerInBo);
        contextServer.setComServer(comServer);
        return contextServer;
    }
}
